<!--* 图片选择组件-->
<!--* 1.dialog的显示: :visible.sync-->
<!--* 2.选择图片后的事件: @choose, 选择后会将图片的所有数据返回-->
<!--* <hj-choose-img :visible.sync="visible"            // 弹框显示控制  (必填)-->
<!--*                @choose="chooseImg"                // 选择图片后的回调方法  (必填)-->
<!--*                auto-crop-width="1000"             // 裁剪框宽度   (非必填)-->
<!--*                auto-crop-height="1000"            // 裁剪框高度   (非必填)-->
<!--*                :fixed="false"                     // 是否固定裁剪框比例   (非必填)-->
<!--*                :fixed-box="false"                 // 是否固定裁剪框尺寸   (非必填)-->
<!--*                @close="visible=false"             // 注意这个visible和:visible.sync中的变量相同, 其实就是为了设置为false-->
<!--*                ></hj-choose-img>-->
<template>
  <div>
    <el-dialog title="选择图片资源" :visible.sync="visible" width="840px" :modal="false" :close-on-click-modal="false" top="1vh" @close="close">
      <div class="choose-image-search-container" style="margin-bottom: 10px;">
        <el-input v-model="fileName" placeholder="请输入文件名" clearable style="width: 160px;" />
        <el-input v-model="extensionName" placeholder="请输入扩展名" clearable style="width: 160px;" />
        <el-select v-model="classificationId" placeholder="请选选择分组" transfer="true" :popper-append-to-body="false" :clearable="true" @change="getList({pageNo: 1})">
          <el-option
            v-for="item in baseClassifyList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="searchImage">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" size="small" @click="showUploadDialog">上传</el-button>
      </div>
      <div class="choose-image-list">
        <div v-for="item in list" :key="item.id" class="choose-image-item">
          <img v-if="item.extensionName !== 'svga'" class="choose-image" :src="cfg.imageDomain + item.path" alt="">
          <svga v-else :src="cfg.imageDomain + item.path" style="height:150px;width:150px" :options="svgaOptions" class="choose-image" />
          <div class="choose-image-size">
            <span>{{ item.width }} * {{ item.height }}</span>
          </div>
          <div class="choose-image-name">
            <span>{{ item.fileName }}</span>
          </div>
          <div class="choose-image-mask">
            <i class="el-icon-zoom-in" @click="previewImg(item)" />
            <i class="el-icon-check" @click="choose(item)" />
            <i class="el-icon-scissors" @click="showCrop(item)" />
          </div>
        </div>
      </div>
      <div>
        <el-pagination
          style="text-align: right"
          layout="prev, pager, next"
          :current-page="pageNo"
          :limit.sync="pageSize"
          :total="total"
          @current-change="pageChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class="upload-img-dialog"
      width="840px"
      title="裁剪"
      :visible.sync="cropperDialogVisible"
    >
      <div style="height: 300px;width:500px;">
        <wj-cropper
          ref="cropperChoose"
          :img="cfg.imageDomain + path"
          :auto-crop-width="boxWidth"
          :auto-crop-height="boxHeight"
          :fixed="fixed"
          :fixed-box="fixedBox"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cropperDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doCrop">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class="upload-img-dialog"
      style="text-align: center"
      width="840px"
      title="预览"
      :visible.sync="previewDialogVisible"
      @close="closePreviewDialog"
    >
      <img v-if="path.indexOf('.svga') === -1" :src="cfg.imageDomain + path" alt="" style="max-height: 400px;max-width: 100%">
      <svga v-else :src="cfg.imageDomain + path" :options="svgaOptions" class="choose-image" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-loading="loading"
      element-loading-text="拼命上传中"
      class="upload-img-dialog"
      width="840px"
      title="上传图片"
      :modal="false"
      :visible.sync="uploadDialogVisible"
    >
      <el-form label-width="100px" class="upload-pic-form">
        <el-form-item label="图片" prop="">
          <el-upload
            :show-file-list="false"
            class="upload-demo"
            accept="image/jpeg,image/gif,image/png,image/jpg,.svg,.svga"
            :before-upload="beforeUploadChooseImage"
            :on-success="chooseImageUploadSuccess"
            :action="cfg.apiDomain + '/file/upload/upload?uploadItem=resPhotoLib'"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img v-if="!!path && suffix === 'gif' || suffix === 'png' || suffix === 'svg'" :src="cfg.imageDomain + path" class="upload-img-preview" alt="">
          <svga v-if="!!path && suffix === 'svga'" :src="cfg.imageDomain + path" :options="svgaOptions" class="upload-img-preview" />
          <div v-if="!!path && suffix !== 'gif' && suffix !== 'png'&& suffix !== 'svg' && suffix !== 'svga'" style="height: 300px;width:500px;">
            <wj-cropper
              ref="cropper"
              :img="cfg.imageDomain + path"
              :auto-crop-width="boxWidth"
              :auto-crop-height="boxHeight"
              :fixed="fixed"
              :fixed-box="fixedBox"
            />
          </div></el-form-item>
        <el-form-item label="自定义文件名">
          <el-input v-model="uploadFileName" placeholder="请输入文件名" maxlength="100" />
        </el-form-item>
        <el-form-item label="图片分类" prop="classificationId">
          <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true" transfer="true" :popper-append-to-body="false">
            <el-option
              v-for="item in baseClassifyList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
          <el-button type="text" @click="refresh">刷新</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUploadFile">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="新增分类" :visible.sync="addClassificationDialog">
      <el-form ref="formData" :rules="formData.rules" label-width="180px">
        <el-form-item label="分类名称">
          <el-input v-model="formData.props.classificationId" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassificationDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="saveClassification">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import WjCropper from './WjCropper'

export default {
  name: 'ChooseImg',
  components: { WjCropper },
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    autoCropWidth: {
      type: Number,
      default: 9999
    },
    autoCropHeight: {
      type: Number,
      default: 9999
    },
    fixed: {
      type: Boolean,
      default: false
    },
    fixedBox: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      svgaOptions: {
        loop: 0,
        fillMode: 'forwards',
        playMode: 'forwards',
        startFrame: 0,
        endFrame: 0,
        autoPlay: true
      },
      imgDialog: false,
      loading: false,
      previewDialogVisible: false,
      cropperDialogVisible: false,
      uploadDialogVisible: false,
      pageNo: 1,
      pageSize: 10,
      total: 0,
      list: [],
      fileName: '',
      fileTypeList: [],
      // 表单保存用的值
      fileType: '',
      // 搜索用的条件
      fileTypeSearch: '',
      uploadFileName: '',
      path: '',
      height: 1,
      width: 1,
      fileSize: '',
      suffix: '',
      boxWidth: 9999,
      boxHeight: 9999,
      extensionName: '',
      baseClassifyList: '',
      classificationId: '',
      btnSubmitDisabled: false,
      addClassificationDialog: false,
      formData: {
        props: {
          classificationId: ''
        },
        rules: {
          classificationId: this.formRules({ required: true })
        }
      }
    }
  },
  watch: {
    visible: function(val) {
      this.imgDialog = val;
    }
  },
  mounted: function() {
    this.boxWidth = this.autoCropWidth;
    this.boxHeight = this.autoCropHeight;
    this.getList({
      pageNo: 1
    });
    this.getBaseClassify();
  },
  methods: {
    getBaseClassify: function() {
      var _this = this;
      request({
        url: '/system/sysBaseParam/selectValueByUnicode?unicode=PHOTO_CLASSIFICATION',
        method: 'post'
      }).then(res => {
        _this.baseClassifyList = res.data.split(',');
      })
    },
    getList: function(param) {
      const _this = this;
      this.pageNo = param.pageNo;
      request({
        method: 'post',
        url: '/res/photoResLib/getPageList',
        data: {
          dataStatus: 1,
          pageNo: param.pageNo,
          pageSize: 10,
          fileName: param.fileName || this.fileName,
          extensionName: param.extensionName || this.extensionName,
          uploaderType: param.type || this.fileTypeSearch,
          classificationId: this.classificationId
        }
      }).then(function(res) {
        const data = res.data;
        _this.total = data.total;
        const rows = data.rows;
        for (let i = 0; i < rows.length; i++) {
          rows[i].fileName = rows[i].fileName.length > 14 ? rows[i].fileName.substr(0, 14) + '...' : rows[i].fileName
        }
        _this.list = rows;
      });
    },
    pageChange: function(pageNo) {
      this.pageNo = pageNo;
      this.getList({
        pageNo: pageNo
      });
    },
    searchImage: function() {
      this.getList({
        pageNo: 1
      });
    },
    choose: function(file) {
      // 如果页面要求裁剪框固定, 那么选择的图片宽高一定要匹配
      if (this.fixedBox) {
        if (file.height !== this.autoCropHeight) {
          this.$message.error('图片高度不匹配');
          return;
        }
        if (file.width !== this.autoCropWidth) {
          this.$message.error('图片宽度不匹配');
          return;
        }
      }
      this.$emit('update:visible', false);
      this.$emit('choose', file);
    },
    showUploadDialog: function() {
      this.path = '';
      this.uploadFileName = '';
      this.fileType = '';
      this.formData.props.classificationId = '';
      this.uploadDialogVisible = true;
    },
    chooseImageUploadSuccess: function(file) {
      this.loading = false;
      const result = file.data;
      this.path = result.key;
      this.height = result.height;
      this.width = result.width;
      this.fileSize = result.fileSize;
      this.suffix = result.suffix;
      this.fileType = '1';
      const _this = this;
      if (result.suffix !== 'png' && result.suffix !== 'gif') {
        setTimeout(function() {
          // 因为裁剪组件有延迟, 我们不是改源码, 所以延迟一下
          const scale = _this.$refs.cropper.$refs.wjCropper.scale;
          _this.boxWidth = _this.autoCropWidth * scale;
          _this.boxHeight = _this.autoCropHeight * scale;
        }, 1000)
      }
    },
    beforeUploadChooseImage: function(file) {
      this.loading = true;
      this.uploadFileName = file.name.substr(0, file.name.lastIndexOf('.'));
      if (file.name.indexOf('.svga') !== -1) {
        this.path = '';
      }
    },
    saveUploadFile: function() {
      const _this = this;
      if (!_this.path) {
        _this.$message.error('请上传图片');
        return;
      }
      if (!_this.uploadFileName) {
        _this.$message.error('请输入文件名');
        return;
      }
      if (!_this.fileType) {
        _this.$message.error('请选择文件类型');
        return;
      }
      // 普通图片要被裁剪并且上传, 所以要调用cropper的上传方法
      if (this.suffix !== 'gif' && this.suffix !== 'png' && this.suffix !== 'svg' && this.suffix !== 'svga') {
        this.$refs.cropper.cropUpload(function(file) {
          var imagesList = [];
          var image = {};
          image.path = file.key;
          image.fileSize = file.fileSize;
          image.extensionName = file.suffix;
          image.imgHeight = file.height;
          image.imgWidth = file.width;
          image.fileName = _this.uploadFileName;
          image.classificationId = _this.formData.props.classificationId;
          image.id = file.id
          imagesList.push(image)
          request({
            method: 'post',
            url: '/res/photoResLib/saveList',
            data: {
              photoReslibMap: imagesList
            }
          }).then(function(res) {
            _this.$message.success('上传成功');
            _this.getList({
              pageNo: 1
            });
            _this.uploadDialogVisible = false;
          });
        })
      } else {
        // 上传的是GIF或者PNG
        request({
          method: 'post',
          url: '/res/photoResLib/save',
          data: {
            path: _this.path,
            fileSize: _this.fileSize,
            extensionName: _this.suffix,
            imgHeight: _this.height,
            imgWidth: _this.width,
            fileName: _this.uploadFileName,
            type: _this.fileType
          }
        }).then(function(res) {
          _this.$message.success('上传成功');
          _this.getList({
            pageNo: 1
          });
          _this.uploadDialogVisible = false;
        });
      }
    },
    /**
       * 显示裁剪弹框
       * @param file
       */
    showCrop: function(file) {
      this.path = file.path;
      this.cropperDialogVisible = true;
      var _this = this;
      setTimeout(function() {
        // 因为裁剪组件有延迟, 我们不是改源码, 所以延迟一下, 500毫秒是测试后最快的值
        var scale = _this.$refs.cropperChoose.$refs.wjCropper.scale;
        _this.boxWidth = _this.autoCropWidth * scale;
        _this.boxHeight = _this.autoCropHeight * scale;
      }, 500)
    },
    /**
       * 裁剪确定
       */
    doCrop: function() {
      var _this = this;
      this.$refs.cropperChoose.cropUpload(function(file) {
        _this.choose({
          fileName: file.fileName,
          fileSize: file.fileSize,
          path: file.key,
          suffix: file.suffix,
          width: file.width,
          height: file.height
        });
        _this.cropperDialogVisible = false;
      })
    },
    previewImg: function(file) {
      this.path = file.path;
      this.previewDialogVisible = true;
    },
    closePreviewDialog() {
      if (this.path && this.path.indexOf('.svga') !== -1) {
        this.path = '';
      }
    },
    close: function() {
      this.$emit('update:visible', false);
      this.$emit('close');
    },
    saveClassification() {
      var _this = this;
      this.baseClassifyList.push(this.formData.props.classificationId);
      const classification = this.baseClassifyList.join(',');
      request({
        url: '/system/sysBaseParam/setValueByUnicode',
        method: 'post',
        data: {
          uniCode: 'PHOTO_CLASSIFICATION',
          value: classification
        }
      }).then(res => {
        _this.addClassificationDialog = false;
        _this.formData.props.classificationId = '';
        _this.$message.success('操作成功');
        _this.getBaseClassify({
        });
      })
    },
    refresh() {
      this.getBaseClassify();
      this.$message.success('刷新成功');
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-pic-form .el-form-item{
  margin-bottom: 10px;
}
</style>
